package com.qs.user.ui.VM;

import android.app.Application;
import android.databinding.BindingAdapter;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.qs.base.data.BaseData;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.utils.BaseTimeUtils;
import com.qs.base.utils.RetrofitClient;
import com.qs.base.utils.SystemUtil;
import com.qs.user.R;
import com.qs.user.api.ApiService;
import com.qs.user.entity.BaseResult;
import com.qs.user.entity.LoginEntity;
import com.qs.user.entity.MemberPriceEntity;
import com.qs.user.entity.PayEntity;
import com.qs.user.pay.entity.SendOrderEntity;
import com.qs.user.pay.util.GeneralUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 会员中心vm
 *
 * @Author ltzz
 * @Date 2019/8/23
 */
public class MemberCenterViewModel extends BaseViewModel {
    public MemberCenterViewModel(@NonNull Application application) {
        super(application);
    }

    //设备id
    public String clientId = "";

    //用户帐号
    public String userId = "";
    //用户名
    public ObservableField<String> userName = new ObservableField<>("未登录");
    //用户头像
    public ObservableField<String> userImg = new ObservableField<>("");
    //会员有效时间
    public ObservableField<String> userDate = new ObservableField<>("开通会员以享受更多服务");
    //会员钱数
    public float money;
    public ObservableField<String> money1 = new ObservableField<>("0");
    public ObservableField<String> money3 = new ObservableField<>("0");
    public ObservableField<String> money12 = new ObservableField<>("0");
    //平均多少钱一个月
    public ObservableField<String> avgMoney3 = new ObservableField<>("0");
    public ObservableField<String> avgMoney12 = new ObservableField<>("0");
    //按钮文字
    public ObservableField<String> buttonStr = new ObservableField<>("支付¥15");
    //会员充值月数
    public int month = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        //查询用户信息
        userId = SPUtils.getInstance().getString(SPKeyGlobal.USER_ID, "");
        userName.set(SPUtils.getInstance().getString(SPKeyGlobal.USER_NAME, "未登录"));
        userImg.set(SPUtils.getInstance().getString(SPKeyGlobal.USER_IMG, ""));
        if (!StringUtils.isTrimEmpty(userId)) {
            //已登录就去服务器查询.
            getVIPInfo(userId);
        }

        getVIPPrice();
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //登录
        public ObservableBoolean login = new ObservableBoolean(false);
        //1月会员
        public ObservableBoolean member1Uc = new ObservableBoolean(false);
        //3月会员
        public ObservableBoolean member3Uc = new ObservableBoolean(false);
        //12月会员
        public ObservableBoolean member12Uc = new ObservableBoolean(false);
        //确认支付
        public ObservableBoolean paymentUc = new ObservableBoolean(false);
        //微信支付
        public ObservableField<String> wxPayUc = new ObservableField<>("");
        //支付宝支付
        public ObservableField<String> aliPayUc = new ObservableField<>("");
    }

    //返回
    public BindingCommand backClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });
    //用户点击
    public BindingCommand userClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (StringUtils.isTrimEmpty(userId))
                uc.login.set(!uc.login.get());
        }
    });
    //1月会员点击
    public BindingCommand member1Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            month = 1;
            uc.member1Uc.set(!uc.member1Uc.get());
        }
    });
    //3月会员点击
    public BindingCommand member3Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            month = 3;
            uc.member3Uc.set(!uc.member3Uc.get());
        }
    });
    //12月会员点击
    public BindingCommand member12Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            month = 12;
            uc.member12Uc.set(!uc.member12Uc.get());
        }
    });
    //确认支付
    public BindingCommand paymentClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.paymentUc.set(!uc.paymentUc.get());
        }
    });

    /**
     * 登录
     *
     * @param imagePath
     * @param pwd
     * @param login
     * @param userName1
     */
    public void register(final String imagePath, final String login, String pwd, final String userName1) {

        String json = GeneralUtils.getJson(new String[]{"User_Name", "User_Phone", "User_Pwd"}, new String[]{StringUtils.isTrimEmpty(userName1) ? "" : userName1, login, pwd});
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .register(BaseData.APPNAME, body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<LoginEntity>() {
                    @Override
                    public void accept(LoginEntity loginEntity) throws Exception {
                        dismissDialog();
                        if ("SUCCESS".equals(loginEntity.getCreateState()) || "Account Exist".equals(loginEntity.getCreateState())) {
                            SPUtils.getInstance().put(SPKeyGlobal.USER_ID, login);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_NAME, userName1);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_IMG, imagePath);
                            ToastUtils.showShort("登录成功");
                            userId = login;
                            userName.set(userName1);
                            userImg.set(imagePath);
                            //请求会员信息
                            getVIPInfo(login);
                        } else {
                            ToastUtils.showShort("登录失败，请重试");
                        }

                        if ("SUCCESS".equals(loginEntity.getCreateState())) {
                            //注册成功，添加剩余数量
                            addNumbers(userId, 400 + "");
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求超时...");
                    }
                });
    }

    /**
     * 获取会员天数价格
     */
    public void getVIPPrice() {
        Map<String, Object> map = new HashMap<>();
        map.put("AppName", BaseData.payName);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getVIPPrice(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<com.qs.user.entity.BaseResult<MemberPriceEntity>>() {
                    @Override
                    public void accept(BaseResult<MemberPriceEntity> baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult != null && baseResult.getList() != null && baseResult.getList().size() > 0) {
                            //成功
                            for (int i = 0; i < baseResult.getList().size(); i++) {
                                switch (baseResult.getList().get(i).getDay()) {
                                    case "30":
                                        money1.set(baseResult.getList().get(i).getPrice());
                                        buttonStr.set("支付¥" + baseResult.getList().get(i).getPrice());
                                        money = Float.parseFloat(money1.get());
                                        break;
                                    case "90":
                                        float price = Float.parseFloat(baseResult.getList().get(i).getPrice());
                                        money3.set(baseResult.getList().get(i).getPrice());
                                        avgMoney3.set(price / 3 + "元/月");
                                        break;
                                    case "365":
                                        float price12 = Float.parseFloat(baseResult.getList().get(i).getPrice());
                                        money12.set(baseResult.getList().get(i).getPrice());
                                        avgMoney12.set(price12 / 12 + "元/月");
                                        break;
                                }
                            }
                        } else {
                            //失败
                            KLog.e("会员价格", "获取失败");
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                    }
                });
    }


    //会员剩余天数
    public void getVIPInfo(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("appname", BaseData.payName);
        map.put("userphone", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getVIPInfo(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        if (baseResult != null) {
                            String day = baseResult.get("day").toString();
                            if (StringUtils.isTrimEmpty(day)) {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, 0);
                            } else {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, day);
                                if (!StringUtils.equals(day, "0")) {
                                    Date date = BaseTimeUtils.dateAddNDay(new Date(), Integer.parseInt(day));
                                    userDate.set(BaseTimeUtils.dateToStringYMDD(date));
                                }
                            }
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                    }
                });
    }

    /**
     * 创建支付信息
     */
    public void creatOrder(String payWay) {
        SendOrderEntity sendOrderEntity = new SendOrderEntity();
        sendOrderEntity.setUser_phone(SPUtils.getInstance().getString(SPKeyGlobal.USER_ID));
        sendOrderEntity.setClient_id(clientId);
        sendOrderEntity.setPhone_type(SystemUtil.getSystemModel());
        sendOrderEntity.setPrice(money+"");//money + ""
        sendOrderEntity.setApp_name(BaseData.payName);//文字扫描精灵
        sendOrderEntity.setCommodity("购买会员");
        if (payWay.equals("微信官方支付")) {
            SendWxOrder(sendOrderEntity);
        } else {
            SendAliOrder(sendOrderEntity);
        }

    }

    /**
     * 发送wx订单
     *
     * @param entity
     */
    private void SendWxOrder(SendOrderEntity entity) {
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(entity));
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .vipPayCreateOrder(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<PayEntity>() {
                    @Override
                    public void accept(PayEntity baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult.getCode() == 1) {
                            uc.wxPayUc.set(baseResult.getPrepay_id());

                        }else{
                            ToastUtils.showShort(baseResult.getMsg());
                        }


                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求出错");
                    }
                });

    }

    /**
     * 发送Ali订单
     *
     * @param entity
     */
    private void SendAliOrder(SendOrderEntity entity) {
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(entity));
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .vipCreateOrder(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<PayEntity>() {
                    @Override
                    public void accept(PayEntity baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult.getCode() == 1) {
                            //调起支付宝支付
                            uc.aliPayUc.set(baseResult.getBody());
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求出错");
                    }
                });

    }


    /**
     * 添加翻译次数
     *
     * @param userid
     * @param wordnumber
     */
    public void addNumbers(String userid, String wordnumber) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        map.put("wordnumber", wordnumber);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(map));

        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .addNumbers(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult != null && Double.parseDouble(baseResult.get("code").toString()) == 0) {

                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                    }
                });
    }


    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView imageView, String url) {
        RequestOptions mRequestOptions = new RequestOptions()
                .override(imageView.getWidth(), imageView.getHeight())
//                .bitmapTransform(new RoundedCorners(5))
                .circleCropTransform()
                .error(R.drawable.user_member_user);
        Glide.with(imageView.getContext())
                .load(url)
                .apply(mRequestOptions)
                .into(imageView);
    }
}
